<template>
	<view>
		<u-navbar title="充值" :placeholder="true" :autoBack="true"></u-navbar>
		<view class="page">
			<view class="top">
				<view class="weixin">
					<text class="label">微信充值余额：</text>
					<text class="money">{{utils.rmoney(Info.aucdeposit.depositBalance)}}</text>
				</view>
				<view class="ptp">
					<text class="label">公对公余额：</text>
					<text
						class="money">{{utils.rmoney(Number(Info.aucdeposit.companyRechargeBalance)+Number(Info.aucdeposit.jietuCompanyRechargeBalance))}}</text>
				</view>
				<view class="inputMoney">
					<view class="text">
						输入充值金额
					</view>
					<view class="inputView">
						<input type="digit" @blur="inputBlur" v-model="price" style="font-size: 60rpx;"
							placeholderStyle="color:#CCCCCC" :placeholder="placeholder" class="amount-input" />
					</view>
				</view>
			</view>
			<view v-if="!realAuthInfo || [3,4].includes(realAuthInfo.status)">
				<view class="shimingTips">
					<view>您当前还未实名认证，请先实名认证</view>
					<view class="shimingTips-right">
						<view @click="toAuth">
							前往认证 >
						</view>
					</view>
				</view>
			</view>
			<view class="type">
				<view class="text">
					选择充值方式
				</view>
				<view v-if="ptp">
					<view class="type-line" data-index="1">
						<view class="type-line-left">
							<view>
								<image src="/static/reCharge/ptp.png" style="width: 50rpx;height: 50rpx;" mode=""></image>
							</view>
							<view class="line-text">
								公对公
							</view>
						</view>
						<view>
							<image src="/static/reCharge/check.png" style="width: 40rpx;height: 40rpx;" mode="">
							</image>
						</view>
					</view>
					<view class="checkAccount" @click="toAccountMan" v-if="realAuthInfo">
						选择账号>
					</view>
					<view>
						<u--form labelPosition="left" labelWidth="auto" :model="form" :rules="rules" ref="uForm">
							<u-form-item label="开户名称：" prop="accountName" required>
								<u--textarea v-model="form.accountName" style="border: none;background-color: #F6F6F6;" disabled
									placeholder="请输入开户名称" autoHeight></u--textarea>
							</u-form-item>
							<view style="font-size: 14px;color: red;margin-left: 10rpx;margin-top: 10rpx;">
								<text>开户名称需与认证名称一致，若账号名称不符请重新编辑账号！</text>
							</view>
							<u-form-item label="银行卡号：" prop="bankCardNo" required>
								<u--textarea autoHeight v-model="form.bankCardNo" style="border: none;background-color: #F6F6F6;"
									placeholder="请输入账号" autoHeight></u--textarea>
							</u-form-item>
							<u-form-item label="银行名称：" prop="bankName" required>
								<u--textarea v-model="form.bankName" style="border: none;background-color: #F6F6F6;" disabled
									placeholder="请输入银行名称，如：招商银行"></u--textarea>
							</u-form-item>
							<u-form-item label="开 户 行：" prop="bankBranch" required>
								<u--textarea v-model="form.bankBranch" style="border: none;background-color: #F6F6F6;" disabled
									placeholder="请输入开户行名称，如：芜湖分行营业部"></u--textarea>
							</u-form-item>
							<u-form-item label="转账用途：" prop="transferPurpose" required>
								<u--input v-model="form.transferPurpose" placeholder="请输入转账用途" border="none" disabled></u--input>
							</u-form-item>
							<u-form-item label="汇款日期：" prop="remittanceTime" required>
								<view @click="showTime = true">
									<u--input placeholder="请选择实际汇款日期" border="none" v-model="form.remittanceTime" readonly></u--input>
								</view>
							</u-form-item>
							<u-form-item label="打款凭证：" prop="proofPayment" required labelPosition="top">
								<view style="margin: 20rpx 0rpx;">
									<u-upload :accept="'image'" multiple @afterRead="afterRead" @delete="deletePic" name="1" :maxCount="1"
										:fileList="fileList1">
										<image src="/static/reCharge/upload.png" mode="widthFix" style="width: 160rpx;height: 160rpx;">
										</image>
									</u-upload>
								</view>
							</u-form-item>
						</u--form>
					</view>
					<u-form-item label="备注：" labelWidth="60" v-if="ptp">
						<u--textarea placeholder="请输入" v-model="remark" border="none" style="background-color: #F6F6F6;"
							maxlength="200"></u--textarea>
					</u-form-item>
				</view>
			</view>
			<view class="btn">
				<view class="tip" v-if="ptp">
					<image src="/static/reCharge/uncheck.png" style="width: 40rpx;height: 40rpx;" v-if="!ischecked"
						@click="ischecked = !ischecked" mode="">
					</image>
					<image src="/static/reCharge/check.png" style="width: 40rpx;height: 40rpx;" v-if="ischecked"
						@click="ischecked = !ischecked" mode="">
					</image>
					<view style="margin-left: 20rpx;">请阅读并同意 <text style="color: blue;" @click="toXieYi">《公对公充值协议》</text> </view>
				</view>
				<u-button color="#28AC3E" text="立即支付" @click="toPay"></u-button>
			</view>
			<view class="tips">
				<text v-html="content"></text>
			</view>
		</view>
		<u-keyboard ref="uKeyboard" mode="number" :showCancel="false" :showConfirm="false" @change="keyboardChange"
			@backspace="backspace" :overlay="false" :show="show"></u-keyboard>
		<u-datetime-picker :show="showTime" v-model="datetimePicker" :maxDate="maxDate" mode="date" @confirm="handleConfirm"
			@cancel="handleClose"></u-datetime-picker>
	</view>
</template>

<script>
	import webUni from "@/common/uni.webview.1.5.2.js";

	const d = new Date()
	const year = d.getFullYear()
	let month = d.getMonth() + 1
	month = month < 10 ? `0${month}` : month
	let date = d.getDate();
	date = date < 10 ? `0${date}` : date

	export default {
		data() {
			return {
				show: false,
				price: '',
				ischecked: false,
				Info: this.$store.state.Info || {
					aucdeposit: {}
				},
				type: 1,
				placeholder: "请输入金额",
				showTime: false,
				maxDate: new Date(`${year}-${month}-${date}`).getTime(),
				minDate: new Date(`${year-20}-${month}-${date-10}`).getTime(),
				datetimePicker: `${year}-${month}-${date}`,
				form: {
					remittanceTime: "",
					accountName: '',
					transferPurpose: "",
					bankCardNo: '',
					bankName: '',
					bankBranch: '',
					proofPayment: ''
				},
				rules: {
					remittanceTime: [{
						required: true,
						message: '请选择汇款日期',
						trigger: ['blur', 'change']
					}],
					accountName: [{
						required: true,
						message: '请填写开户名称',
						trigger: ['blur', 'change']
					}],
					transferPurpose: [{
						required: true,
						message: '请填写转账用途',
						trigger: ['blur', 'change']
					}],
					bankCardNo: [{
						required: true,
						message: '请填写银行卡号',
						trigger: ['blur', 'change']
					}],
					bankName: [{
						required: true,
						message: '请填写银行名称',
						trigger: ['blur', 'change']
					}],
					bankBranch: [{
						required: true,
						message: '请填写开户支行',
						trigger: ['blur', 'change']
					}],
					proofPayment: [{
							required: true,
							message: '请上传打款凭证',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								console.log(value);
								return value ? true : false;
							},
							message: '请上传打款凭证',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
				},
				fileList1: [],
				content: null,
				urlParams: this.$store.state.urlParams,
				remark: "",
				isDisabled: false,
				isDisabledAccountName: false,
				ptpInputTips: 0,
				proofPaymentHash: [],
				currentHash: {},
				hashValue: 0,
				weixin: false,
				ptp: false,
				realAuthInfo: null,
				JTH5_code_switch: false,
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			// this.$refs.uForm.setRules(this.rules)
		},
		async onLoad() {
			uni.$on("accountItem", (data) => {
				this.form.accountName = data.accountName;
				this.form.bankCardNo = data.bankCardNo;
				this.form.bankName = data.bankName;
				this.form.bankBranch = data.bankBranch;
			})
			await this.getAgreement();
			this.ptp = await this.getDictOne("JTH5_reCharge_ptp") == 1;
			this.ptpInputTips = await this.getDictOne("JTH5_reCharge_ptp_minPrice");
			this.JTH5_code_switch = await this.getDictOne("JTH5_code_switch") == 1;
			this.form.transferPurpose = uni.getStorageSync("Info").manufactureName + " + " + uni.getStorageSync("urlParams")
				.erpCode +
				" + 置换充值"
			this.placeholder = `请输入金额，${this.ptpInputTips}元起`
			this.realAuthInfo = await this.realAuthDetail();
			// let that = this;
			// window.PaySuccess = function(data) { //支付成功
			// 	console.log("接收app回调消息", data);
			// 	if (data.errMsg == "requestPayment:ok") {
			// 		uni.navigateTo({
			// 			url: `/pages/reCharge/success?payType=${that.type == 0 ? '02' : '03'}&price=${that.price}`
			// 		})
			// 	}
			// }
		},
		onShow() {
			this.getCallinfoInfo();
		},
		onUnload() {
			uni.$off("accountItem")
		},
		methods: {
			//查询实名信息
			async realAuthDetail() {
				let result = await this.api.realAuthDetail();
				return result.data.data;
			},
			//跳转认证页面
			toAuth() {
				if (this.JTH5_code_switch) {
					uni.navigateTo({
						url: "/pages/authentication/index"
					})
				} else {
					uni.navigateTo({
						url: "/pages/realNameAuth/index"
					})
				}
			},
			//获取协议
			getAgreement() {
				this.api.getAgreement("czsm").then(res => {
					console.log(res);
					this.content = res.data.data.content;
				})
			},
			toAccountMan() {
				uni.navigateTo({
					url: "/pages/accountMan/index"
				})
			},
			async getDictOne(code) {
				let res = await this.api.getDictOne(code);
				console.log(res, 111);
				return res.data.data.dictValue;
			},
			handleConfirm(e) {
				this.form.remittanceTime = this.timestampToDate(e.value)
				this.showTime = false;
			},
			handleClose() {
				this.showTime = false;
			},
			//格式化时间
			timestampToDate(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day} 00:00:00`;
			},
			removeTrailingParentheses(str) {
				return str.replace(/(.*?)([\(（][^\)）]*[\)）])$/, "$1");
			},
			toXieYi() {
				uni.navigateTo({
					url: "/pages/precautions/index?code=gdgczxy"
				})
			},
			getAccountName() {
				this.api.getaccountname({
					...uni.getStorageSync("urlParams")
				}).then(res => {
					console.log(res.data.data);
					let name = res.data.data;
					// let name = "泰安亿车行汽车销售服务(芜湖)有限公司"
					this.form.accountName = this.removeTrailingParentheses(name);
				})
			},
			/**
			 * 查询账户信息
			 */
			getCallinfoInfo(options) {
				let params = {
					...uni.getStorageSync("urlParams")
				}
				this.api.getCallinfoInfo(params).then(
					res => {
						if (!res.data.data.erpCode) {
							uni.showModal({
								title: '提示',
								content: '未查询到相关信息！！',
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
										webUni.postMessage({
											data: {
												type: "back",
												data: []
											},
										})
									}
								}
							});
						}
						this.Info = res.data.data;
						uni.setStorageSync("Info", res.data.data);
						uni.setStorageSync("wxUserInfo", {
							openId: res.data.data.openId,
							unionId: res.data.data.unionId,
							wxNickName: res.data.data.wxNickName,
						});
					})
			},
			//正则匹配金额
			inputBlur(e) {
				console.log(e.target.value);
				// 正则表达式
				const regex = /^\d+(\.\d{0,2})?$/;

				if (!regex.test(e.target.value)) {
					uni.$u.toast("请输入正确金额")
				}
			},
			/**
			 * 查询账号信息
			 */
			getAccountInfo() {
				this.api.getAccountInfo({
					...uni.getStorageSync("urlParams")
				}).then(res => {
					console.log("res--->", res.data.data);
					if (res.data.data) {
						if (res.data.data.bankName || res.data.data.bankCardNo || res.data.data.bankBranch) {
							this.isDisabled = false;
						}
						this.proofPaymentHash = res.data.data.proofPaymentHash ? res.data.data.proofPaymentHash.split(",") : [];
					}
					if (!res.data.data || !res.data.data.accountName) {
						this.getAccountName();
					} else {
						this.form.accountName = this.removeTrailingParentheses(res.data.data.accountName);
						this.isDisabledAccountName = true
					}
				})
			},
			rightClick() {},
			/** 查询字典类型详细 */
			getDict() {

			},
			//立即支付
			async toPay() {
				if (!this.ptp) {
					return
				}
				this.realAuthInfo = await this.realAuthDetail();
				if (!this.realAuthInfo || [3, 4].includes(this.realAuthInfo.status)) {
					uni.$u.toast("充值需完成实名认证，请您先实名认证！");
					return;
				}
				if (this.price == "") {
					uni.$u.toast('请输入充值金额');
					return
				}
				if(this.realAuthInfo.name != this.form.accountName){
					return uni.$u.toast("开户名称与认证名称不符，重新编辑账号！");
				}
				const moneyRegex = /^\d+(\.\d{0,2})?$/;
				if (!moneyRegex.test(this.price)) {
					uni.$u.toast("请输入正确金额");
					return
				}
				let that = this;
				if (!this.ischecked) {
					uni.$u.toast("请阅读并同意《公对公充值协议》")
					return
				}
				if (Number(this.price) < this.ptpInputTips) {
					uni.$u.toast(`公对公充值金额不能小于${this.ptpInputTips}元`);
					return
				}
				that.$refs.uForm.validate().then((valid) => {
					if (valid) {
						uni.showModal({
							title: '请确认是否继续申请公对公充值？',
							content: '请确认使用的公对公账户信息与上传打款凭证中使用的账户信息一致，否则将影响本次充值结果，请在申请充值前仔细阅读充值页面下方的注意事项！',
							success: function(res) {
								if (res.confirm) {
									// if (that.currentHash.isSame) {
									// 	that.$u.toast("当前打款凭证已提交申请，请勿重复提交!")
									// 	return
									// }
									uni.showLoading({
										title: '提交中...',
										mask: true,
									});
									that.api.recharge({
										...uni.getStorageSync("urlParams"),
										price: that.price,
										...that.form,
										remark: that.remark,
										payType: '03',
										// proofPaymentHash: that.currentHash.currentHash
									}).then(res => {
										uni.hideLoading()
										if (res.data.code == 200) {
											uni.$u.toast("提交成功，请耐心等待审核！");
											uni.navigateTo({
												url: `/pages/reCharge/success?payType=03&price=${that.price}`
											})
										}
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				}).catch(errors => {})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
				this.form.proofPayment = ""
			},
			// 新增图片
			async afterRead(event) {
				console.log(event);
				let regex = /\.([a-zA-Z0-9]+)$/;
				let name = event.file[0].name
				const match = name.match(regex);
				console.log(match);
				if (!['jpg', 'jpeg', 'png'].includes(match[1])) {
					this.$u.toast(`请上传格式为${['jpg','jpeg','png'].join('/')}的图片`);
					return;
				}
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFile(lists[i].url);
					console.log(result);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
				console.log(this.fileList1);
				this.form.proofPayment = this.fileList1[0].url
				this.compareWithHistory(this.form.proofPayment, this.proofPaymentHash, this.hashValue).then(res => {
					console.log(res);
					this.currentHash = res;
				})

			},
		}
	}
</script>

<style scoped lang="scss">
	page {
		background-color: #F6F6F6;
		// height: 50vh;
		overflow-y: auto;
	}

	.page {
		margin: 20rpx;
	}

	.tip {
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 24rpx;
		line-height: 33rpx;
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.shimingTips {
		background-color: #F8DD02;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 10rpx;
		margin-top: 20rpx;
		font-size: 22rpx;
		font-weight: bold;

		.shimingTips-left {}

		&-right {
			display: flex;
			align-items: center;
			color: #15298C;
		}
	}

	.checkAccount {
		display: flex;
		align-items: center;
		justify-content: end;
		color: #9295F7;
		font-size: 25rpx;
		font-weight: bold;
		margin: 10rpx 10rpx;
	}

	::v-deep .u-form-item__body {
		padding: 20rpx 25rpx;
		background-color: #F6F6F6;
		border-radius: 10rpx;
		margin: 10rpx 0rpx;

		.u-form-item__body__left__content__label {
			font-weight: 500;
		}
	}

	.top {
		padding: 20rpx;
		background-color: #FFFFFF;
	}

	.label {
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #999999;
		line-height: 40rpx;
	}

	.money {
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 32rpx;
		color: #333333;
		line-height: 45rpx;
	}

	.weixin {}

	.ptp {
		margin-top: 20rpx;
	}

	.inputMoney {
		margin-top: 40rpx;
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 34rpx;
		color: #333333;
		line-height: 45rpx;

		.inputView {
			width: 90%;
			margin-top: 20rpx;
		}
	}

	.type {
		margin-top: 20rpx;
		padding: 20rpx;
		background-color: #FFFFFF;

		.text {
			font-family: PingFang SC;
			font-weight: bold;
			font-size: 32rpx;
			color: #333333;
			line-height: 45rpx;
		}
	}

	.type-line {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 30rpx;
		padding: 10rpx 20rpx;

		.type-line-left {
			display: flex;
		}

		.line-text {
			margin-left: 20rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 30rpx;
			color: #333333;
			line-height: 42rpx;
		}
	}

	.remark {
		display: flex;
		margin-top: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 28rpx;
		color: #333333;
		line-height: 40rpx;
	}

	.btn {
		margin: 30rpx 40rpx;
	}

	.tips {
		margin: 30rpx 20rpx;
		padding: 10rpx;
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 24rpx;
		color: #666666;
		line-height: 40rpx;
	}
</style>